package com.ticket.sass.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.OrderCouponMapMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.OrderCouponMapEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2024-04-17 14:36
 */
@Service
public class OrderCouponMapServiceImpl extends ServiceImpl<OrderCouponMapMapper, OrderCouponMapEntity> implements BaseService<OrderCouponMapEntity> {
    /**
     * 根据订单ID列表查询对应的订单优惠券关联列表，并按订单ID分组返回
     *
     * @param orderIds 订单ID列表
     * @return Map，键是订单ID，值是相应的订单优惠券关联列表
     */
    public Map<Long, List<OrderCouponMapEntity>> getOrderCouponMapByOrderIds(List<Long> orderIds) {
        if (orderIds.size() == 0) {
            return new HashMap<>();
        }
        
        // 使用 MyBatis-Plus 的 selectList 方法根据订单ID列表查询对应的订单优惠券关联列表
        QueryWrapper<OrderCouponMapEntity> aNull = new QueryWrapper<OrderCouponMapEntity>().in("map.order_id", orderIds).isNull("coupon.deleted_at");
        aNull.isNull("map.deleted_at");
        
        List<OrderCouponMapEntity> orderCouponMaps = baseMapper.queryList(aNull);
        
        // 使用 Java 8 的流式操作将结果列表按订单ID分组为一个 Map
        
        return orderCouponMaps.stream()
            .collect(Collectors.groupingBy(OrderCouponMapEntity::getOrderId));
    }
    
    public List<Long> orderIdsBy(List<Long> couponIds) {
        if (CollectionUtil.isEmpty(couponIds)) {
            return new ArrayList<>();
        }
        
        QueryWrapper<OrderCouponMapEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("coupon_id", couponIds);
        queryWrapper.select("order_id");
        return this.listObjs(queryWrapper, obj -> (Long) obj);
    }
}
